<template>
  <div class="incident-page">
    <div class="header-bar">
      <h1 class="page-title">事件处理</h1>
    </div>

    <div class="filter-bar">
      <div class="filter-item search-item">
        <label for="keyword-filter">搜索:</label>
        <input id="keyword-filter" type="text" v-model="filters.keyword" placeholder="按类型、地点、描述搜索...">
      </div>
      <div class="filter-item">
        <label for="status-filter">状态:</label>
        <select id="status-filter" v-model="filters.status">
          <option value="全部">全部</option>
          <option value="0">未处理</option>
          <option value="1">处理中</option>
          <option value="2">已处理</option>
        </select>
      </div>
      <button class="btn btn-primary" @click="applyFilters">应用筛选</button>
      <button class="btn btn-secondary" @click="resetFilters">重置</button>
    </div>

    <div class="incident-grid">
      <div v-if="paginatedList.length === 0" class="empty-data-card">根据当前筛选条件，暂无事件记录</div>
      <div v-for="incident in paginatedList" :key="incident.incidentId" class="incident-card">
        <div class="card-header">
          <h4 class="title">{{ incident.incidentType }} - {{ getLocationDisplay(incident) }}</h4>
        </div>
        <div class="card-body">
          <div class="info-row"><span class="label">报告时间:</span> <span class="value">{{ formatDateTime(incident.reportTime) }}</span></div>
          <div class="info-row">
            <span class="label">完成时间:</span> <!-- 新增完成时间 -->
            <span class="value">{{ formatDateTime(incident.completeTime) }}</span>
          </div>
          <div class="info-row">
            <span class="label">处理警员:</span> <!-- 新增处理警员 -->
            <span class="value officer-name">{{ incident.officerName || '未指派' }}</span>
          </div>
          <div class="info-row">
            <span class="label">状态:</span>
            <span :class="['status-badge', getStatusClass(incident.incidentStatus)]">{{ getStatusDisplay(incident.incidentStatus) }}</span>
          </div>
          <div class="info-row location-info">
            <span class="label">位置:</span>
            <span class="value">
              {{ getLocationDisplay(incident) }}
            </span>
          </div>
          <div class="info-row description">
            <span class="label">描述:</span>
            <span class="value">{{ incident.description }}</span>
          </div>
        </div>
        <div class="card-footer">
          <button class="btn-action btn-detail" @click="openDetailModal(incident)">查看详情</button>
          <button class="btn-action btn-assign" @click="assignPolice(incident)">指派警力</button>
        </div>
      </div>
    </div>

    <Pagination
      v-if="filteredList.length > itemsPerPage"
      :current-page="currentPage"
      :total-pages="totalPages"
      @page-changed="handlePageChange"
    />

    <IncidentDetailModal
      v-if="isModalOpen"
      :incident="selectedIncident"
      @close="closeModal"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue';
import { useRouter } from 'vue-router';
import IncidentDetailModal from './IncidentDetailModal.vue';
import Pagination from '@/components/Pagination.vue';
import api from '@/utils/axios';
import axios from "axios";

const API_BASE = 'http://localhost:8080/api/auth';
const router = useRouter();

// 模拟数据
const incidentList = ref<any[]>([]);

// 状态枚举映射（后端数字到中文描述）
const statusMapChinese = {
  'UNPROCESSED': '未处理',
  'PROCESSING': '处理中',
  'COMPLETED': '已处理'
};

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '';
  // 假设后端返回的是ISO格式的字符串，如 "2025-06-20T10:30:00"
  const date = new Date(dateTime);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

const statusClassMap = {
  'UNPROCESSED': 'status-待处理',
  'PROCESSING': 'status-处理中',
  'COMPLETED': 'status-已解决'
};

// 获取状态显示文本
const getStatusDisplay = (status: number | string) => {
  const statusKey = status.toString();
  return statusMapChinese[statusKey as keyof typeof statusMapChinese] || statusKey;
};

// 获取状态对应的CSS类名
const getStatusClass = (status: string) => {
  return statusClassMap[status as keyof typeof statusClassMap] || 'status-unknown';
};

// 高德地图API配置
const AMAP_API_KEY = 'e67f0e9520643f148baa0e9747a27038';

// 获取地址信息的函数
const getAddressByCoordinates = async (lng: number, lat: number) => {
  try {
    const response = await axios.get(`https://restapi.amap.com/v3/geocode/regeo?key=${AMAP_API_KEY}&location=${lng},${lat}`);
    if (response.data.status === '1') {
      return response.data.regeocode.formatted_address;  // 返回格式化的地址
    }
    return null;
  } catch (error) {
    console.error('获取地址信息失败:', error);
    return null;
  }
};

// 处理位置显示（同步版本）
const getLocationDisplay = (incident: any) => {
  if (incident.coordinates && incident.coordinates.length >= 2) {
    const lng = parseFloat(incident.coordinates[0].toString()).toFixed(6);
    const lat = parseFloat(incident.coordinates[1].toString()).toFixed(6);

    // 如果有地址信息，直接返回
    if (incident.location) {
      return incident.location;
    }

    // 没有地址信息，返回经纬度
    return `经度: ${lng}, 纬度: ${lat}`;
  }
  return '位置未知';
};

// 为事件添加位置信息
const addLocationInfoToIncidents = async () => {
  for (const incident of incidentList.value) {
    if (incident.coordinates && incident.coordinates.length >= 2) {
      const lng = parseFloat(incident.coordinates[0].toString());
      const lat = parseFloat(incident.coordinates[1].toString());

      try {
        const address = await getAddressByCoordinates(lng, lat);
        if (address) {
          incident.location = address;
        }
      } catch (error) {
        console.error('获取地址信息失败:', error);
      }
    }
  }
};

// 筛选与分页
const filters = reactive({ keyword: '', status: '全部' });
const activeFilters = reactive({ keyword: '', status: '全部' });
const applyFilters = () => { Object.assign(activeFilters, filters); };
const resetFilters = () => { Object.assign(filters, { keyword: '', status: '全部' }); applyFilters(); };

const filteredList = computed(() => {
  return incidentList.value.filter(item => {
    const statusMatch = activeFilters.status === '全部' || item.incidentStatus.toString() === activeFilters.status;
    const keyword = activeFilters.keyword.trim().toLowerCase();
    const keywordMatch = !keyword ||
      item.incidentType.toLowerCase().includes(keyword) ||
      (item.location && item.location.toLowerCase().includes(keyword)) ||
      (item.coordinates && item.coordinates.toString().toLowerCase().includes(keyword)) ||
      item.description.toLowerCase().includes(keyword);
    return statusMatch && keywordMatch;
  });
});

const currentPage = ref(1);
const itemsPerPage = ref(6);
const totalPages = computed(() => Math.ceil(filteredList.value.length / itemsPerPage.value));
const paginatedList = computed(() => {
  const start = (currentPage.value - 1) * itemsPerPage.value;
  return filteredList.value.slice(start, start + itemsPerPage.value);
});
const handlePageChange = (page: number) => { currentPage.value = page; };
watch(activeFilters, () => { currentPage.value = 1; });

// 弹窗逻辑
const isModalOpen = ref(false);
const selectedIncident = ref<any>(null);
const openDetailModal = (incident: any) => { selectedIncident.value = incident; isModalOpen.value = true; };
const closeModal = () => { isModalOpen.value = false; };

// 指派警力跳转
const assignPolice = (incident: any) => {
  router.push({ name: 'Dispatch', query: { eventId: incident.incidentId } });
};

// 加载事件列表
const loadIncidents = async () => {
  try {
    const response = await api.get(`${API_BASE}/incidents`);
    // 转换数据格式
    incidentList.value = response.data.map((incident: any) => ({
      ...incident,
      // 确保状态值是字符串形式的数字
      incidentStatus: incident.incidentStatus?.toString() || '0'
    }));
    console.log(incidentList)

    // 获取地址信息并添加到事件数据中
    await addLocationInfoToIncidents();
  } catch (error) {
    console.error('Error fetching incidents:', error);
  }
};

loadIncidents();
</script>

<style scoped>
@import "@/assets/styles/views/dashboard/Incident.css";
</style>
